package com.xu.cloud.common.api;

import org.springframework.core.NamedThreadLocal;
import org.springframework.lang.NonNull;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;

import java.util.Objects;

/**
 * 本地线程缓存ApiContext参数
 *
 * @author xuguan
 * @since 2024/1/9
 */
public class ApiContextHolder {

    private static final ThreadLocal<ApiContext> TRANS_CONTEXT_THREAD = new NamedThreadLocal<>("transContextThreadLocal");

    public static void setRequestContext(@NonNull ApiContext requestContext) {
        Assert.notNull(requestContext, "HttpRequestContext must not be null");
        TRANS_CONTEXT_THREAD.set(requestContext);
    }

    @Nullable
    public static ApiContext getTransContext() {
        return TRANS_CONTEXT_THREAD.get();
    }

    @NonNull
    public static ApiContext getOrSetTransContext() {
        ApiContext requestContext = TRANS_CONTEXT_THREAD.get();
        if (Objects.isNull(requestContext)) {
            requestContext = new ApiContext();
            TRANS_CONTEXT_THREAD.set(requestContext);
        }
        return requestContext;
    }

    public static void remove() {
        TRANS_CONTEXT_THREAD.remove();
    }
}
